package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"time"
	"webgogo/models"
	"webgogo/util"
)

// Operations about ApiBlog
type BlogApiController struct {
	beego.Controller
}

// @Title Get Page Info List
// @Description 按照分页获取文章列表
// @Param	:page 	ID 	int	true	"Page id"
// @Param	size 	pagesize 	int	false	"size of one page"
// @Success 200 string "json string of page info"
// @router /page/list/:page [get]
func (c *BlogApiController) ListPages() {
	nSize, _ := c.GetInt("size", 10)
	nPage, _ := c.GetInt(":page", 0)
	nPages := 0
	retJson := make(map[string]interface{})

	queryList := util.Ormer.QueryTable(models.PageInfo{}).Filter("Type", 0)
	nSizeAll, err := queryList.Count()
	if err == nil {
		var nSizeAll_ = int(nSizeAll)
		var nSizeLast = nSizeAll_ % nSize
		if nSizeLast == 0 {
			nPages = int(nSizeAll_ / nSize)
			nSizeLast = nSize
		} else {
			nPages = int(nSizeAll_/nSize + 1)
		}

	}
	retJson["page"] = nPage
	retJson["pages"] = nPages
	retJson["size"] = nSize
	retJson["sizeall"] = nSizeAll

	var pageList []*models.PageInfo
	queryList.OrderBy("-id").Limit(nSize, (nPage)*nSize).RelatedSel("Cate", "Tag").All(&pageList)
	retJson["data"] = pageList

	c.Data["json"] = retJson
	c.ServeJSON()
}

// @Title Get Page Content
// @Description 按照ID获取文章内容
// @Param	:ID 	ID 	int	true	"Page id"
// @Success 200 {object} models.PageInfo
// @router /page/view/:ID [get]
func (c *BlogApiController) ViewByID() {
	nID, _ := c.GetInt(":ID", 0)

	var pageInfo = models.PageInfo{Id: nID}
	if nil == util.Ormer.Read(&pageInfo) {
		util.Ormer.LoadRelated(&pageInfo, "Cate")
		util.Ormer.LoadRelated(&pageInfo, "Tag")
		util.Ormer.LoadRelated(&pageInfo, "Content")
	}

	c.Data["json"] = pageInfo
	c.ServeJSON()
}

// @Title Edit Page
// @Description 编辑一篇文章，不存在则添加
// @Param	page_id 	ID 	int	true	"Page id, -1 means add"
// @Param	cate_id 	cate 	int	true	"cate id"
// @Param	tag_id 	tag 	int	true	"tag id"
// @Param	author 	author 	string	false	"作者"
// @Param	title 	title 	string	true	"文章标题"
// @Param	describe 	describe 	false	true	"文章简介"
// @Param	content 	content 	string	true	"内容"
// @Param	type 	type 	int	false	"文章类型"
// @Success 200 string "json string of page info"
// @router /page/edit [post]
func (c *BlogApiController) EditByID() {
	nPageID, _ := c.GetInt("id", -1)
	nCateID, _ := c.GetInt("cate_id", -1)
	nTagID, _ := c.GetInt("tag_id", -1)
	strAuthor := c.GetString("author", "Admin")
	strTitle := c.GetString("title", "")
	strDescribe := c.GetString("describe", "")
	strContent := c.GetString("content", "")
	var nLen = len(strContent)
	if len(strTitle) == 0 {
		if nLen < 20 {
			strTitle = strContent
		} else {
			strTitle = strContent[0:20]
		}
	}

	if len(strDescribe) == 0 {
		if nLen < 120 {
			strTitle = strContent
		} else {
			strTitle = strContent[0:120]
		}
	}

	// make
	var pageInfo = models.PageInfo{}
	if nPageID > 0 {
		pageInfo.Id = nPageID
		if nil == util.Ormer.Read(&pageInfo) {
			util.Ormer.LoadRelated(&pageInfo, "Content")
		}
		pageInfo.Content.Text = strContent
		pageInfo.Content.EditTime = time.Now()
		util.Ormer.Update(&pageInfo.Content)
		sql := "UPDATE `page_info` SET `cate_id` = ?,`tag_id` = ?,`author` = ?,`title` = ?,`describtion` = ?	,`content_id` = ? WHERE id=?;"
		util.Ormer.Raw(sql, nCateID, nTagID, strAuthor, strTitle, strDescribe, pageInfo.Content.Id, pageInfo.Id).Exec()
	} else {
		// insert
		var pageCont = models.PageContent{}
		pageCont.Text = strContent
		util.Ormer.Insert(&pageCont)

		sql := "INSERT INTO `page_info` (`cate_id`,`tag_id`,`author`,`title`,`describtion`,`content_id`,`add_time`,`type`) VALUES(?,?,?,?,?,?,?,?)"
		result, err := util.Ormer.Raw(sql, nCateID, nTagID, strAuthor, strTitle, strDescribe, pageCont.Id, time.Now(), 0).Exec()
		if err != nil {
			fmt.Println(result, err)
		}

	}

	c.Data["json"] = pageInfo
	c.ServeJSON()
}

// @Title Get Category list
// @Description 获取文章分类列表
// @Success 200 string "json string of category list"
// @router /category [get]
func (c *BlogApiController) ListCategory() {
	retJson := make(map[string]interface{})
	var blogCategory []*models.BlogCategory
	util.Ormer.QueryTable(models.BlogCategory{}).All(&blogCategory)

	retJson["data"] = blogCategory
	c.Data["json"] = retJson
	c.ServeJSON()
}

// @Title Edit Category
// @Description 修改文章分类
// @Param	id 	ID 	int	true	"category id, -1 means add"
// @Param	url 	urlName 	string	true	"url name"
// @Param	name 	showname 	string	true	"show name"
// @Param	descr 	describtion 	string	false	"describtion"
// @Success 200 string "json string of category info"
// @router /category/edit [post]
func (c *BlogApiController) EditCategory() {
	nID, _ := c.GetInt("id", -1)
	strUrl := c.GetString("url", "")
	strName := c.GetString("name", "")
	strDescr := c.GetString("descr", "")

	retJson := make(map[string]interface{})
	var blogCategory models.BlogCategory

	blogCategory.UrlName = strUrl
	blogCategory.ShowName = strName
	blogCategory.Describtion = strDescr

	if nID > 0 {
		// update
		blogCategory.Id = nID

		util.Ormer.Update(&blogCategory)
	} else {
		util.Ormer.Insert(&blogCategory)
	}

	retJson["data"] = blogCategory
	c.Data["json"] = retJson
	c.ServeJSON()
}

// @Title Get Category Page list
// @Description 通过分类获取文章列表
// @Success 200 string "json string of page list"
// @router /category/:ID [get]
func (c *BlogApiController) ListPageByCategory() {
	retJson := make(map[string]interface{})
	nID, _ := c.GetInt(":ID", 0)
	var pageList []*models.PageInfo
	util.Ormer.QueryTable(models.PageInfo{}).RelatedSel("Cate", "Tag").Filter("Cate__ID", nID).All(&pageList)
	retJson["data"] = pageList

	c.Data["json"] = retJson
	c.ServeJSON()
}

// @Title Get Tag Page list
// @Description 通过标签获取文章列表
// @Success 200 string "json string of Tag list"
// @router /tag/:ID [get]
func (c *BlogApiController) ListPageByTag() {
	retJson := make(map[string]interface{})
	nID, _ := c.GetInt(":ID", 0)
	var pageList []*models.PageInfo
	util.Ormer.QueryTable(models.PageInfo{}).RelatedSel("Cate", "Tag").Filter("Tag__ID", nID).All(&pageList)
	retJson["data"] = pageList

	c.Data["json"] = retJson
	c.ServeJSON()
}

// @Title Edit Tag
// @Description 修改文章Tag
// @Param	id 	ID 	int	true	"tag id, -1 means add"
// @Param	url 	urlName 	string	true	"url name"
// @Param	name 	showname 	string	true	"show name"
// @Param	descr 	describtion 	string	false	"describtion"
// @Success 200 string "json string of tag info"
// @router /tag/edit [post]
func (c *BlogApiController) EditTag() {
	nID, _ := c.GetInt("id", -1)
	strUrl := c.GetString("url", "")
	strName := c.GetString("name", "")
	strDescr := c.GetString("descr", "")

	retJson := make(map[string]interface{})
	var blogTag models.BlogTag

	blogTag.UrlName = strUrl
	blogTag.ShowName = strName
	blogTag.Describtion = strDescr

	if nID > 0 {
		// update
		blogTag.Id = nID
		util.Ormer.Update(&blogTag)

	} else {
		util.Ormer.Insert(&blogTag)
	}

	retJson["data"] = blogTag
	c.Data["json"] = retJson
	c.ServeJSON()
}

// @Title sync db table
// @Description 获取用户信息
// @Param	force 	force 	int	false	"if not 0, rebuild db tables"
// @Success 200 string "json ok"
// @router /syncdb [get]
func (c *BlogApiController) SyncDB() {
	retJson := make(map[string]interface{})
	nForce, _ := c.GetInt(":force", 0)
	bForce := false
	if nForce != 0 {
		bForce = true
	}
	orm.RunSyncdb("default", bForce, true)
	retJson["ret"] = "ok"
	c.Data["json"] = retJson
	c.ServeJSON()
}

// @Title Get User Info
// @Description 获取用户信息
// @Success 200 {object} models.BlogUser
// @router /user/:ID [get]
func (c *BlogApiController) UserInfo() {
	nID, _ := c.GetInt(":ID", 0)

	var userInfo = models.BlogUser{Id: nID}
	util.Ormer.Read(&userInfo)

	c.Data["json"] = userInfo
	c.ServeJSON()
}

// @Title Edit User info
// @Description 修改用户信息
// @Param	id 	ID 	int	true	"user id, -1 means add"
// @Param	url 	urlName 	string	true	"url"
// @Param	name 	showname 	string	true	"name"
// @Param	type 	type 	int	false	"describtion"
// @Success 200 {object} models.BlogUser
// @router /user/edit [post]
func (c *BlogApiController) UserEdit() {
	nID, _ := c.GetInt(":ID", 0)
	strUrl := c.GetString("url", "")
	strName := c.GetString("name", "")
	nType, _ := c.GetInt("type", 0)

	var userInfo = models.BlogUser{}
	userInfo.Url = strUrl
	userInfo.Name = strName
	userInfo.Type = int8(nType)

	if nID > 0 {
		userInfo.Id = nID
		util.Ormer.Update(&userInfo)
	} else {
		util.Ormer.Insert(&userInfo)
	}

	c.Data["json"] = userInfo
	c.ServeJSON()
}
